package me.listcircular;

import java.util.Iterator;

public class DoublyLinkedListCircular implements Iterable<Integer> {
    // 双向循环链表
    public static class Node {
        Node prev; // 上一节点指针
        int value;
        Node next; // 下一节点指针

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    // 哨兵节点
    private Node sentinel = new Node(null, -1, null);

    public DoublyLinkedListCircular() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    // 1.头插
    public void addFirst(int value) {
        Node a = sentinel;
        Node b = sentinel.next;
        Node added = new Node(a, value, b);
        a.next = added;
        b.prev = added;
    }

    // 2.尾插
    public void addLast(int value) {
        Node a = sentinel.prev;
        Node b = sentinel;
        Node added = new Node(a, value, b);
        a.next = added;
        b.prev = added;
    }

    // 3.头删
    public void removeFirst() {
        Node removed = sentinel.next;
        if (removed == sentinel) {
            throw new IllegalArgumentException("非法");
        }
        Node a = removed.next;
        Node b = sentinel;
        b.next = a;
        a.prev = b;
    }

    // 4.尾删
    public void removeLast() {
        Node removed = sentinel.prev;
        if (removed == sentinel) {
            throw new IllegalArgumentException("非法");
        }
        Node a = removed.prev;
        Node b = sentinel;
        a.next = b;
        b.prev = a;
    }

    // 5.根据值查找节点
    public Node findByValue(int value) {
        Node p = sentinel.next;
        while (p != sentinel) {
            if (value == p.value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }

    // 6.根据值删除
    public void removeByValue(int value) {
        Node removed = findByValue(value);
        if (removed == null) {
            return;//不删
        }
        Node a = removed.prev;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }

    // 迭代器遍历
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = sentinel.next;

            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    // 打印链表
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node p = sentinel.next;
        while (p != sentinel) {
            sb.append(p.value).append(" -> ");
            p = p.next;
        }
        sb.append(sentinel.next.value);
        return sb.toString();
    }
}
